package de.fhkiel.webstore.utils;

import java.util.HashMap;
import javax.servlet.http.HttpSession;

public class SessionHelper
{
	private static final String ITEM_IDS = "itemid";
	
    public static void addItem( HttpSession session, Object item ) {
    	if ( session == null )
    		return;
    	
    	HashMap<Long, Integer> items = getItems( session );
    	Integer value = items.get( item );
    	value = ( value == null ) ? 1 : ++value;
    	items.put( (Long) item, value );
    	session.setAttribute( ITEM_IDS, items );
    }
    
    public static void subItem( HttpSession session, Object item ) {
    	if ( session == null )
    		return;
    	
    	HashMap<Long, Integer> items = getItems( session );
    	Integer value = items.get( item );
    	if( value == null || value == 1 ) {
    		removeItem( session, item );
    		return;
    	}
    	value--;
    		
    	items.put( (Long) item, value );
    	session.setAttribute( ITEM_IDS, items );
    }
    
    public static void removeItem( HttpSession session, Object item ) {
    	if ( session == null )
    		return;
    	
    	HashMap<Long, Integer> items = getItems( session );
    	if ( items.get( item ) != null ) {
    		items.remove( item );
    		session.setAttribute( ITEM_IDS, items );
    	}
    }

    public static void cleanItems( HttpSession session ) {
        if ( session == null )
            return;
        
        session.removeAttribute( ITEM_IDS );
    }

    public static HashMap<Long, Integer> getItems( HttpSession session ) {
        if ( session != null ) {
            Object items = session.getAttribute( ITEM_IDS );
            if( items != null ) {
                return ( HashMap<Long, Integer> ) items;
            }
        }
        return new HashMap<Long, Integer>();
    }
}
